import { useState, useEffect } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
import { Bot, Filter, RefreshCw, Search, Calendar, Repeat, List } from 'lucide-react'
import AISuggestionCard from '../components/AISuggestionCard'
import TaskSection from '../components/TaskSection'
import EmptyState from '../components/EmptyState'
import TaskFilterPanel from '../components/TaskFilterPanel'
import PageTransition, { AnimatedCardList } from '../components/PageTransition'
import { useModernNotification } from '../components/ModernNotification'
import { useAuth } from '../contexts/AuthContext'
import { aiAPI, taskAPI } from '../services/api'
import { Task, AISuggestion } from '../types'
import { 
  FilterOptions, 
  SortOption, 
  SortDirection, 
  defaultFilterOptions,
  // filterTasks,
  // sortTasks,
  getFilterDisplayText,
  getSortDisplayText
} from '../utils/taskFilters'
import { TimeUtils } from '../utils/timeUtils'
import {
  getAIPreferences,
  shouldAutoLoadSuggestions,
  toggleAISuggestions,
  recordAISuggestionShown,
  recordAISuggestionDismissed,
  shouldShowIntroduction,
  markIntroductionSeen
} from '../utils/aiPreferences'

export default function HomePage() {
  const navigate = useNavigate()
  const location = useLocation()
  const { showNotification, NotificationComponent } = useModernNotification()
  const { user } = useAuth()
  const [activeTab, setActiveTab] = useState<'today' | 'recurring' | 'all'>('today')
  const [tasks, setTasks] = useState<{ overdue: Task[], today: Task[], upcoming: Task[], noDate: Task[] }>({
    overdue: [],
    today: [],
    upcoming: [],
    noDate: []
  })
  const [suggestions, setSuggestions] = useState<AISuggestion[]>([])
  const [showSuggestions, setShowSuggestions] = useState(() => {
    // 从用户偏好中读取初始状态
    const preferences = getAIPreferences()
    return preferences.enabled && preferences.showOnHomepage
  })
  const [isLoadingSuggestions, setIsLoadingSuggestions] = useState(false)
  const [showAIIntro, setShowAIIntro] = useState(() => shouldShowIntroduction())
  // const [allTasks, setAllTasks] = useState<Task[]>([])
  const [filters, setFilters] = useState<FilterOptions>(defaultFilterOptions)
  const [sortBy, setSortBy] = useState<SortOption>('dueDate')
  const [sortDirection, setSortDirection] = useState<SortDirection>('asc')
  const [showFilterPanel, setShowFilterPanel] = useState(false)
  const [notification, setNotification] = useState<{
    message: string
    type: 'success' | 'error' | 'info'
  } | null>(null)

  // 建议状态持久化相关
  const DISMISSED_SUGGESTIONS_KEY = 'aide_dismissed_suggestions'
  const ACCEPTED_SUGGESTIONS_KEY = 'aide_accepted_suggestions'
  const SUGGESTIONS_CACHE_KEY = 'aide_suggestions_cache'
  const SUGGESTIONS_CACHE_TIME_KEY = 'aide_suggestions_cache_time'
  const CACHE_DURATION = 30 * 60 * 1000 // 30分钟缓存

  useEffect(() => {
    // 根据路径设置活动标签页
    if (location.pathname.startsWith('/recurring')) {
      setActiveTab('recurring')
    } else {
      setActiveTab('today')
    }
  }, [location.pathname])

  useEffect(() => {
    // 清理过期数据
    cleanupExpiredData()
    
    // 加载任务数据
    loadTasks()
    
    // 智能加载AI建议 - 只有在用户偏好允许时才自动加载
    if (shouldAutoLoadSuggestions()) {
      console.log('用户偏好允许，自动加载AI建议')
      loadAISuggestionsWithCache()
    } else {
      console.log('用户偏好不允许自动加载AI建议，等待手动触发')
    }
  }, [])

  // 清理过期的localStorage数据
  const cleanupExpiredData = () => {
    const now = Date.now()
    const maxAge = 7 * 24 * 60 * 60 * 1000 // 7天
    
    // 清理过期的已处理建议记录
    const cleanupSuggestionIds = (key: string) => {
      try {
        const stored = localStorage.getItem(key)
        if (stored) {
          // 如果数据超过7天，清空记录
          const lastCleanup = localStorage.getItem(`${key}_last_cleanup`)
          if (!lastCleanup || (now - parseInt(lastCleanup, 10)) > maxAge) {
            localStorage.setItem(key, '[]')
            localStorage.setItem(`${key}_last_cleanup`, now.toString())
            console.log(`已清理过期的${key}数据`)
          }
        }
      } catch (error) {
        console.warn(`清理${key}数据时出错:`, error)
        localStorage.removeItem(key)
      }
    }
    
    cleanupSuggestionIds(DISMISSED_SUGGESTIONS_KEY)
    cleanupSuggestionIds(ACCEPTED_SUGGESTIONS_KEY)
  }

  const loadTasks = async () => {
    try {
      const allTasks = await taskAPI.getAllTasks()
      
      // 处理重复任务去重 - 相同parent_recurring_id的重复任务只显示最近的一个
      const processedTasks = allTasks.reduce((acc, task: any) => {
        if (task.isRecurring && task.parentRecurringId) {
          // 查找是否已有相同parent_recurring_id的重复任务
          const existingIndex = acc.findIndex((t: any) => 
            t.isRecurring && 
            t.parentRecurringId === task.parentRecurringId
          )
          
          if (existingIndex >= 0) {
            // 如果找到相同的重复任务，保留日期更近的那个（或未完成的）
            const existing = acc[existingIndex]
            const taskDate = new Date(task.dueDate || '1970-01-01')
            const existingDate = new Date(existing.dueDate || '1970-01-01')
            
            // 优先显示未完成的任务，其次是日期更近的任务
            if (!task.completed && existing.completed) {
              acc[existingIndex] = { ...task, recurringInstanceCount: (existing.recurringInstanceCount || 1) + 1 }
            } else if (task.completed === existing.completed && taskDate > existingDate) {
              acc[existingIndex] = { ...task, recurringInstanceCount: (existing.recurringInstanceCount || 1) + 1 }
            } else {
              // 只增加计数
              acc[existingIndex].recurringInstanceCount = (existing.recurringInstanceCount || 1) + 1
            }
          } else {
            // 新的重复任务
            acc.push({ ...task, recurringInstanceCount: 1 })
          }
        } else {
          // 非重复任务直接添加
          acc.push(task)
        }
        return acc
      }, [] as any[])
      
      // 将任务按时间分组 - 使用统一的时间工具
      const todayStr = TimeUtils.formatDate(new Date(), 'YYYY-MM-DD')
      
      const taskData = {
        overdue: processedTasks.filter(task => {
          if (!task.dueDate || task.completed) return false
          const dueDateStr = task.dueDate.split('T')[0] // 只取日期部分
          return dueDateStr < todayStr
        }).map(task => ({
          ...task,
          dueDate: task.dueDate ? new Date(task.dueDate) : undefined,
          createdAt: new Date(task.createdAt),
          updatedAt: new Date(task.updatedAt),
          priority: task.priority as 'P0' | 'P1' | 'P2' | 'P3',
          category: task.category as 'work' | 'personal' | 'learning' | 'health' | 'other',
          subtasks: [] // API返回的任务没有subtasks字段，设为空数组
        })),
        today: processedTasks.filter(task => {
          if (!task.dueDate || task.completed) return false
          const dueDateStr = task.dueDate.split('T')[0] // 只取日期部分
          return dueDateStr === todayStr
        }).map(task => ({
          ...task,
          dueDate: task.dueDate ? new Date(task.dueDate) : undefined,
          createdAt: new Date(task.createdAt),
          updatedAt: new Date(task.updatedAt),
          priority: task.priority as 'P0' | 'P1' | 'P2' | 'P3',
          category: task.category as 'work' | 'personal' | 'learning' | 'health' | 'other',
          subtasks: []
        })),
        upcoming: processedTasks.filter(task => {
          if (!task.dueDate || task.completed) return false
          const dueDateStr = task.dueDate.split('T')[0] // 只取日期部分
          return dueDateStr > todayStr
        }).map(task => ({
          ...task,
          dueDate: task.dueDate ? new Date(task.dueDate) : undefined,
          createdAt: new Date(task.createdAt),
          updatedAt: new Date(task.updatedAt),
          priority: task.priority as 'P0' | 'P1' | 'P2' | 'P3',
          category: task.category as 'work' | 'personal' | 'learning' | 'health' | 'other',
          subtasks: []
        })),
        noDate: processedTasks.filter(task => !task.dueDate && !task.completed).map(task => ({
          ...task,
          dueDate: task.dueDate ? new Date(task.dueDate) : undefined,
          createdAt: new Date(task.createdAt),
          updatedAt: new Date(task.updatedAt),
          priority: task.priority as 'P0' | 'P1' | 'P2' | 'P3',
          category: task.category as 'work' | 'personal' | 'learning' | 'health' | 'other',
          subtasks: []
        }))
      }
      setTasks(taskData)
    } catch (error) {
      console.error('加载任务失败:', error)
      setTasks({ overdue: [], today: [], upcoming: [], noDate: [] })
    }
  }

  // 获取已处理的建议ID
  const getProcessedSuggestionIds = () => {
    const dismissed = JSON.parse(localStorage.getItem(DISMISSED_SUGGESTIONS_KEY) || '[]')
    const accepted = JSON.parse(localStorage.getItem(ACCEPTED_SUGGESTIONS_KEY) || '[]')
    return new Set([...dismissed, ...accepted])
  }

  // 检查缓存是否有效
  const isCacheValid = () => {
    const cacheTime = localStorage.getItem(SUGGESTIONS_CACHE_TIME_KEY)
    if (!cacheTime) return false
    
    const now = Date.now()
    const cacheTimestamp = parseInt(cacheTime, 10)
    return (now - cacheTimestamp) < CACHE_DURATION
  }

  // 智能加载建议（带缓存和去重）
  const loadAISuggestionsWithCache = async () => {
    try {
      // 1. 检查缓存
      if (isCacheValid()) {
        const cachedSuggestions = localStorage.getItem(SUGGESTIONS_CACHE_KEY)
        if (cachedSuggestions) {
          const suggestions = JSON.parse(cachedSuggestions)
          const processedIds = getProcessedSuggestionIds()
          const filteredSuggestions = suggestions.filter((s: AISuggestion) => !processedIds.has(s.id))
          
          if (filteredSuggestions.length > 0) {
            console.log('使用缓存的建议:', filteredSuggestions.length, '条')
            setSuggestions(filteredSuggestions)
            return
          }
        }
      }

      // 2. 缓存无效或没有可显示的建议，重新获取
      console.log('重新获取AI建议...')
      await loadAISuggestions()
    } catch (error) {
      console.error('智能加载建议时出错:', error)
      setSuggestions([])
    }
  }

  // 基于内容的建议去重
  const isDuplicateSuggestion = (newSuggestion: AISuggestion, existingSuggestions: AISuggestion[]) => {
    const newMessage = newSuggestion.content.toLowerCase()
    
    return existingSuggestions.some(existing => {
      const existingMessage = existing.content.toLowerCase()
      
      // 检查相似度：如果有80%以上的相同词汇，认为是重复
      const newWords = newMessage.split(/\s+/)
      const existingWords = existingMessage.split(/\s+/)
      
      const commonWords = newWords.filter((word: string) => 
        word.length > 2 && existingWords.includes(word)
      )
      
      const similarity = commonWords.length / Math.max(newWords.length, existingWords.length)
      return similarity > 0.6 // 60%相似度阈值
    })
  }

  const loadAISuggestions = async (forceRefresh = false) => {
    // 防止重复调用：如果正在加载中，直接返回
    if (isLoadingSuggestions) {
      console.log('AI建议正在加载中，跳过重复调用')
      return
    }
    
    try {
      setIsLoadingSuggestions(true)
      
      // 构造Dashboard场景上下文（统计与时间上下文）
      const allForStats = [
        ...tasks.overdue,
        ...tasks.today,
        ...tasks.upcoming,
        ...tasks.noDate,
      ]
      const overdueCount = tasks.overdue.length
      const todayCount = tasks.today.length
      const upcomingCount = tasks.upcoming.length
      const noDateCount = tasks.noDate.length
      const recurringCount = allForStats.filter((t: any) => t.isRecurring).length
      const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone
      const now = new Date()
      const isWeekend = now.getDay() === 0 || now.getDay() === 6
      const isWorkingHours = now.getHours() >= 9 && now.getHours() <= 18
      const dashboardContext = `仪表盘上下文:\n- 过期: ${overdueCount} 条\n- 今天: ${todayCount} 条\n- 未来: ${upcomingCount} 条\n- 无日期: ${noDateCount} 条\n- 重复任务: ${recurringCount} 条\n时间上下文:\n- 当前: ${now.toLocaleString('zh-CN')}\n- 时区: ${timezone}\n- 是否周末: ${isWeekend ? '是' : '否'}\n- 是否工作时间: ${isWorkingHours ? '是' : '否'}`

      // 使用个性化建议API（dashboard模式）；未登录则退化为基础建议
      let result: any
      if (user?.id) {
        result = await aiAPI.getPersonalizedSuggestions(dashboardContext, { mode: 'dashboard' })
      } else {
        result = await aiAPI.getSuggestions()
      }
      if (result.success && result.suggestions) {
        // 转换API返回的建议格式为前端需要的格式
        const formattedSuggestions = result.suggestions.map((suggestion: any) => ({
          id: suggestion.id || `suggestion_${Date.now()}_${Math.random()}`,
          type: suggestion.type || 'general',
          title: suggestion.title || '智能建议',
          content: suggestion.message || suggestion.content || '暂无内容',
          priority: suggestion.priority || 'medium' as 'high' | 'medium' | 'low',
          reasoning: suggestion.reasoning,
          createdAt: suggestion.createdAt || new Date().toISOString(),
          actions: [
            { label: '接受建议', action: 'accept', primary: true },
            { label: '忽略', action: 'dismiss', primary: false }
          ]
        }))

        // 仪表盘建议白名单过滤（双保险）
        const DASHBOARD_ALLOWED_TYPES = new Set(['workload_balance', 'deadline_reminder', 'habit_optimization', 'efficiency_tip', 'auto_schedule'])
        const sceneFiltered = formattedSuggestions.filter((s: any) => DASHBOARD_ALLOWED_TYPES.has(s.type))
        
        // 获取历史建议进行去重（只在非强制刷新时使用历史建议）
        const historicalSuggestions: AISuggestion[] = []
        if (!forceRefresh) {
          try {
            const cachedSuggestions = localStorage.getItem(SUGGESTIONS_CACHE_KEY)
            if (cachedSuggestions) {
              historicalSuggestions.push(...JSON.parse(cachedSuggestions))
            }
          } catch (error) {
            console.warn('读取历史建议失败:', error)
          }
        }
        
        // 内容去重：过滤与历史建议相似的新建议
        const deduplicatedSuggestions = sceneFiltered.filter((newSuggestion: AISuggestion) => 
          !isDuplicateSuggestion(newSuggestion, historicalSuggestions)
        )
        
        // 过滤已处理的建议
        const processedIds = getProcessedSuggestionIds()
        const filteredSuggestions = deduplicatedSuggestions.filter((s: AISuggestion) => !processedIds.has(s.id))
        
        // 限制显示的建议数量（最多显示5条）
        const limitedSuggestions = filteredSuggestions.slice(0, 5)
        
        // 缓存建议
        const allSuggestions = forceRefresh ? deduplicatedSuggestions : [...historicalSuggestions, ...deduplicatedSuggestions]
        localStorage.setItem(SUGGESTIONS_CACHE_KEY, JSON.stringify(allSuggestions))
        localStorage.setItem(SUGGESTIONS_CACHE_TIME_KEY, Date.now().toString())
        
        setSuggestions(limitedSuggestions)
        console.log(`${forceRefresh ? '强制刷新' : '常规加载'}获取到新建议:`, formattedSuggestions.length, '条')
        console.log('去重后建议:', deduplicatedSuggestions.length, '条')
        console.log('最终显示建议:', limitedSuggestions.length, '条')
      } else {
        console.warn('AI建议加载失败:', result.error)
        setSuggestions([])
      }
    } catch (error) {
      console.error('加载AI建议时出错:', error)
      setSuggestions([])
    } finally {
      setIsLoadingSuggestions(false)
    }
  }

  const handleToggleComplete = async (taskId: string) => {
    try {
      // 找到要更新的任务
      let targetTask: Task | undefined
      let targetSection: 'overdue' | 'today' | 'upcoming' | 'noDate' | undefined
      
      if (tasks.overdue.find(t => t.id === taskId)) {
        targetTask = tasks.overdue.find(t => t.id === taskId)
        targetSection = 'overdue'
      } else if (tasks.today.find(t => t.id === taskId)) {
        targetTask = tasks.today.find(t => t.id === taskId)
        targetSection = 'today'
      } else if (tasks.upcoming.find(t => t.id === taskId)) {
        targetTask = tasks.upcoming.find(t => t.id === taskId)
        targetSection = 'upcoming'
      } else if (tasks.noDate.find(t => t.id === taskId)) {
        targetTask = tasks.noDate.find(t => t.id === taskId)
        targetSection = 'noDate'
      }
      
      if (!targetTask || !targetSection) return
      
      // 调用API更新任务状态
      const result = await taskAPI.toggleTask(taskId)
      if (result.message) {
        // 更新本地状态
        setTasks(prev => ({
          ...prev,
          [targetSection]: prev[targetSection].map(task => 
            task.id === taskId ? { ...task, completed: !task.completed } : task
          )
        }))
      }
    } catch (error) {
      console.error('更新任务状态失败:', error)
      alert('更新任务状态失败，请重试')
    }
  }

  const handleTaskClick = (taskId: string) => {
    navigate(`/task/${taskId}`)
  }

  // 删除任务
  const handleDeleteTask = async (taskId: string) => {
    try {


      await taskAPI.deleteTask(taskId)
      // 重新加载任务数据
      await loadTasks()
      
      setNotification({
        message: '任务已删除',
        type: 'success'
      })
      
      // 3秒后自动隐藏通知
      setTimeout(() => setNotification(null), 3000)
    } catch (error) {
      console.error('删除任务失败:', error)
      setNotification({
        message: '删除任务失败，请重试',
        type: 'error'
      })
      setTimeout(() => setNotification(null), 3000)
    }
  }

  const handleFiltersChange = (newFilters: FilterOptions) => {
    setFilters(newFilters)
  }

  const handleSortChange = (newSortBy: SortOption, newDirection: SortDirection) => {
    setSortBy(newSortBy)
    setSortDirection(newDirection)
  }

  const handleResetFilters = () => {
    setFilters(defaultFilterOptions)
    setSortBy('dueDate')
    setSortDirection('asc')
  }

  const isFiltersActive = () => {
    return JSON.stringify(filters) !== JSON.stringify(defaultFilterOptions) ||
           sortBy !== 'dueDate' || 
           sortDirection !== 'asc'
  }

  const handleAcceptSuggestion = async (suggestion: AISuggestion) => {
    try {
      console.log('接受建议:', suggestion)
      
      // 1. 记录到localStorage
      const accepted = JSON.parse(localStorage.getItem(ACCEPTED_SUGGESTIONS_KEY) || '[]')
      accepted.push(suggestion.id)
      localStorage.setItem(ACCEPTED_SUGGESTIONS_KEY, JSON.stringify(accepted))
      
      // 2. 调用API记录用户接受了建议（使用真实用户ID）
      if (user?.id) {
        await aiAPI.recordSuggestionFeedback(suggestion.id, 'accept', 5, '用户接受了建议')
      }
      
      // 3. 从列表中移除
      setSuggestions(prev => prev.filter(s => s.id !== suggestion.id))
      
      console.log('建议已接受并记录反馈')
    } catch (error) {
      console.error('处理建议时出错:', error)
      // 即使API调用失败，也要从UI中移除建议并记录到localStorage
      setSuggestions(prev => prev.filter(s => s.id !== suggestion.id))
      throw error // 重新抛出错误以便组件处理
    }
  }

  const handleDismissSuggestion = async (suggestion: AISuggestion) => {
    try {
      console.log('忽略建议:', suggestion)
      
      // 1. 记录到localStorage
      const dismissed = JSON.parse(localStorage.getItem(DISMISSED_SUGGESTIONS_KEY) || '[]')
      dismissed.push(suggestion.id)
      localStorage.setItem(DISMISSED_SUGGESTIONS_KEY, JSON.stringify(dismissed))
      
      // 2. 调用API记录用户忽略了建议（使用真实用户ID）
      if (user?.id) {
        await aiAPI.recordSuggestionFeedback(suggestion.id, 'dismiss', 2, '用户忽略了建议')
      }
      
      // 3. 从列表中移除
      setSuggestions(prev => prev.filter(s => s.id !== suggestion.id))
      
      console.log('建议已忽略并记录反馈')
    } catch (error) {
      console.error('处理建议时出错:', error)
      // 即使API调用失败，也要从UI中移除建议并记录到localStorage
      setSuggestions(prev => prev.filter(s => s.id !== suggestion.id))
      throw error // 重新抛出错误以便组件处理
    }
  }

  // 处理AI建议的具体动作 - 使用AI智能参数解析
  const handleSuggestionAction = async (suggestion: AISuggestion, action: string) => {
    try {
      console.log('执行建议动作:', action, suggestion)
      
      // 获取相关任务上下文（如果存在）
      let taskContext = null
      if (suggestion.taskId) {
        const allTasks = [...tasks.overdue, ...tasks.today, ...tasks.upcoming, ...tasks.noDate]
        taskContext = allTasks.find(t => t.id === suggestion.taskId)
      }
      
      // 使用AI智能解析动作参数
      const parseResult = await aiAPI.parseActionParameters(suggestion, action, taskContext)
      
      if (!parseResult.success) {
        alert('参数解析失败，请重试')
        return
      }
      
      const { result } = parseResult
      if (!result) {
        alert('参数解析失败：返回结果为空')
        return
      }
      
      const { parameters, reasoning, confidence, requiresUserInput, userPrompt } = result
      
      console.log('🤖 AI智能解析结果:', {
        action,
        parameters,
        reasoning,
        confidence,
        requiresUserInput
      })
      
      // 如果AI建议需要用户输入，显示提示
      if (requiresUserInput && userPrompt) {
        const userInput = prompt(userPrompt)
        if (!userInput) {
          console.log('用户取消了输入')
          return
        }
        
        // 根据动作类型处理用户输入
        if (action.includes('time') || action.includes('date')) {
          try {
            const inputDate = new Date(userInput)
            if (!isNaN(inputDate.getTime())) {
              parameters.dueDate = inputDate.toISOString()
            } else {
              alert('日期格式不正确')
              return
            }
          } catch (error) {
            alert('日期格式不正确')
            return
          }
        } else if (action.includes('priority')) {
          if (['P0', 'P1', 'P2', 'P3'].includes(userInput)) {
            parameters.priority = userInput
          } else {
            alert('优先级格式不正确，请使用 P0/P1/P2/P3')
            return
          }
        }
      }
      
      // 执行任务更新
      if (suggestion.taskId && Object.keys(parameters).length > 0) {
        const updateData: any = {}
        
        // 构建更新数据
        if (parameters.dueDate) updateData.dueDate = parameters.dueDate
        if (parameters.priority) updateData.priority = parameters.priority
        if (parameters.status) updateData.status = parameters.status
        if (parameters.category) updateData.category = parameters.category
        if (parameters.reminderMinutes) updateData.reminderMinutes = parameters.reminderMinutes
        if (parameters.notes) updateData.notes = parameters.notes
        
        // 特殊处理完成状态
        if (parameters.status === 'done') {
          await taskAPI.toggleTask(suggestion.taskId)
        } else if (Object.keys(updateData).length > 0) {
          await taskAPI.updateTask(suggestion.taskId, updateData)
        }
        
        // 显示成功消息
        const actionMessages = {
          'adjust_date': '任务时间已调整',
          'adjust_time': '任务时间已调整',
          'change_due_date': '任务截止日期已更新',
          'elevate_priority': '任务优先级已提升',
          'lower_priority': '任务优先级已降低',
          'mark_complete': '任务已标记为完成',
          'mark_in_progress': '任务已标记为进行中',
          'mark_preparing': '任务已标记为进行中',
          'set_reminder': '提醒已设置',
          'set_10min_reminder': '10分钟提醒已设置'
        }
        
        const message = actionMessages[action as keyof typeof actionMessages] || `动作"${action}"执行成功`
        showNotification({
          title: '操作成功',
          message: message,
          type: 'success',
          details: {
            aiExplanation: reasoning,
            confidence: confidence
          },
          duration: 3000
        })
        
        // 重新加载任务数据
        await loadTasks()
      } else {
        // 对于不需要更新任务的动作，显示通用消息
        const generalMessages = {
          'accept': '建议已接受',
          'dismiss': '建议已忽略',
          'snooze': '稍后会再次提醒您',
          'merge_drink_reminders': '喝水提醒已合并',
          'end_work_today': '建议您结束今日工作，保持工作与生活的平衡！',
          'plan_tomorrow': '建议您规划明日日程，提前准备可以提高效率！',
          'breakdown_task': '任务分解功能正在开发中...',
          'optimize_schedule': '日程优化建议已应用',
          'balance_workload': '工作量平衡建议已应用'
        }
        
        const message = generalMessages[action as keyof typeof generalMessages] || `执行动作: ${action}`
        showNotification({
          title: '操作完成',
          message: message,
          type: 'success',
          duration: 3000
        })
      }
      
      // 记录动作执行（使用真实用户ID）
      if (user?.id) {
        await aiAPI.recordSuggestionFeedback(suggestion.id, action, 5, `用户执行了动作: ${action}`)
      }
      
      // 从列表中移除建议
      setSuggestions(prev => prev.filter(s => s.id !== suggestion.id))
      
    } catch (error) {
      console.error('执行建议动作失败:', error)
      showNotification({
        title: '操作失败',
        message: '执行动作失败，请重试',
        type: 'error',
        duration: 4000
      })
    }
  }

  const handleTabSwitch = (tab: 'today' | 'recurring' | 'all') => {
    setActiveTab(tab)
    if (tab === 'recurring') {
      navigate('/recurring')
    } else if (tab === 'today') {
      navigate('/')
    }
    // 'all' tab will be handled in the current page
  }

  const totalTasks = tasks.overdue.length + tasks.today.length + tasks.upcoming.length + tasks.noDate.length

  return (
    <PageTransition>
      <div className="min-h-screen">
        <NotificationComponent />
      {/* 清爽顶部导航栏 */}
      <div className="nav-card sticky top-0 z-50">
        <div className="flex items-center justify-between px-6 py-4">
          <div className="flex items-center space-x-4">
            <div className="flex items-center space-x-3">
              <div className="w-8 h-8 bg-blue-600 rounded-lg flex items-center justify-center">
                <Bot size={16} className="text-white" />
              </div>
              <h1 className="text-2xl font-bold text-slate-900">
                AIDE
              </h1>
            </div>
            
            <div className="text-sm text-slate-500 ml-4">
              {totalTasks > 0 ? `${totalTasks} 个任务` : '暂无任务'}
            </div>
          </div>
          
          <div className="flex items-center space-x-2">
            {/* 搜索功能 */}
            <button
              onClick={() => navigate('/search')}
              className="p-2.5 rounded-xl transition-all duration-200 bg-slate-100 text-slate-600 hover:bg-slate-200"
              title="搜索任务"
            >
              <Search size={18} />
            </button>
            
            {/* 筛选功能 */}
            <button
              onClick={() => setShowFilterPanel(!showFilterPanel)}
              className={`relative p-2.5 rounded-xl transition-all duration-200 ${
                isFiltersActive() 
                  ? 'bg-blue-600 text-white shadow-md' 
                  : 'bg-slate-100 text-slate-600 hover:bg-slate-200'
              }`}
              title="筛选和排序"
            >
              <Filter size={18} />
              {isFiltersActive() && (
                <div className="absolute -top-1 -right-1 w-2 h-2 bg-orange-400 rounded-full"></div>
              )}
            </button>
            
            {/* AI建议控制 */}
            <button
              onClick={async () => {
                const newShowState = !showSuggestions
                setShowSuggestions(newShowState)
                
                // 保存用户偏好
                const enabled = toggleAISuggestions(newShowState)
                console.log('AI建议开关状态:', enabled)
                
                // 如果用户开启建议且当前没有建议，则加载建议
                if (newShowState && suggestions.length === 0 && !isLoadingSuggestions) {
                  console.log('用户开启AI建议，开始加载...')
                  await loadAISuggestionsWithCache()
                }
                
                // 记录用户操作
                if (newShowState) {
                  recordAISuggestionShown()
                } else {
                  recordAISuggestionDismissed()
                }
              }}
              className={`relative p-2.5 rounded-xl transition-all duration-200 ${
                showSuggestions 
                  ? 'bg-blue-600 text-white shadow-md' 
                  : 'bg-slate-100 text-slate-600 hover:bg-slate-200'
              }`}
              title={showSuggestions ? '隐藏AI建议' : '显示AI建议'}
            >
              <Bot size={18} />
              {suggestions.length > 0 && showSuggestions && (
                <div className="absolute -top-1 -right-1 w-2 h-2 bg-green-500 rounded-full"></div>
              )}
            </button>
          </div>
        </div>
        
        {/* 标签页切换 */}
        <div className="px-6 py-2 border-b border-slate-200">
          <div className="flex space-x-1">
            {[
              { key: 'today', label: '今天', icon: Calendar },
              { key: 'recurring', label: '重复', icon: Repeat },
              { key: 'all', label: '全部', icon: List }
            ].map(({ key, label, icon: Icon }) => (
              <button
                key={key}
                onClick={() => handleTabSwitch(key as 'today' | 'recurring' | 'all')}
                className={`flex items-center space-x-2 px-4 py-2 rounded-lg text-sm font-medium transition-all duration-200 ${
                  activeTab === key
                    ? 'bg-blue-600 text-white shadow-sm'
                    : 'text-slate-600 hover:bg-slate-100'
                }`}
              >
                <Icon size={14} />
                <span>{label}</span>
              </button>
            ))}
          </div>
        </div>
        
        {/* 筛选状态显示 */}
        {isFiltersActive() && (
          <div className="px-6 py-3 bg-blue-50 border-b border-blue-200 animate-fade-in-up">
            <div className="flex items-center justify-between">
              <div className="flex-1">
                <p className="text-xs text-blue-700 font-medium">
                  筛选: {getFilterDisplayText(filters)}
                </p>
                <p className="text-xs text-blue-600">
                  排序: {getSortDisplayText(sortBy, sortDirection)}
                </p>
              </div>
              <button
                onClick={handleResetFilters}
                className="text-xs text-blue-600 hover:text-blue-800 px-2 py-1 rounded-lg hover:bg-blue-100 transition-colors"
              >
                清除
              </button>
            </div>
          </div>
        )}
      </div>

      {/* AI建议首次使用引导 */}
      {showAIIntro && (
        <div className="mx-4 mb-4 p-4 bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200 rounded-xl animate-fade-in-up">
          <div className="flex items-start gap-3">
            <div className="w-8 h-8 bg-blue-600 rounded-lg flex items-center justify-center flex-shrink-0 mt-1">
              <Bot size={16} className="text-white" />
            </div>
            <div className="flex-1">
              <h3 className="text-sm font-semibold text-blue-900 mb-1">
                🎉 欢迎使用AI智能建议功能！
              </h3>
              <p className="text-xs text-blue-700 mb-3 leading-relaxed">
                AI助手可以根据您的任务情况提供个性化建议，帮助您提高工作效率。
                您可以随时通过右上角的机器人图标开启或关闭此功能。
              </p>
              <div className="flex gap-2">
                <button
                  onClick={() => {
                    markIntroductionSeen()
                    setShowAIIntro(false)
                    // 开启AI建议
                    const enabled = toggleAISuggestions(true)
                    setShowSuggestions(true)
                    if (enabled && suggestions.length === 0) {
                      loadAISuggestionsWithCache()
                    }
                  }}
                  className="px-3 py-1.5 bg-blue-600 text-white text-xs font-medium rounded-lg hover:bg-blue-700 transition-colors"
                >
                  开启AI建议
                </button>
                <button
                  onClick={() => {
                    markIntroductionSeen()
                    setShowAIIntro(false)
                  }}
                  className="px-3 py-1.5 bg-slate-200 text-slate-700 text-xs font-medium rounded-lg hover:bg-slate-300 transition-colors"
                >
                  暂不使用
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* AI智能建议区 */}
      {showSuggestions && (
        <div className="mb-4 pt-4 md:pt-4">
          {suggestions.length > 0 ? (
            <>
              <AnimatedCardList>
                {suggestions.map((suggestion) => (
                  <AISuggestionCard
                    key={suggestion.id}
                    suggestion={suggestion}
                    onAccept={handleAcceptSuggestion}
                    onDismiss={handleDismissSuggestion}
                    onAction={handleSuggestionAction}
                  />
                ))}
              </AnimatedCardList>
              
              {/* 刷新建议按钮 */}
              <div className="mx-4 mb-4 text-center">
                <button
                  onClick={async () => {
                    // 防止重复点击
                    if (isLoadingSuggestions) return
                    
                    // 强制刷新建议（清除缓存）
                    localStorage.removeItem(SUGGESTIONS_CACHE_KEY)
                    localStorage.removeItem(SUGGESTIONS_CACHE_TIME_KEY)
                    await loadAISuggestions(true)
                  }}
                  disabled={isLoadingSuggestions}
                  className={`p-2 rounded-lg transition-colors hover-lift ${
                    isLoadingSuggestions
                      ? 'text-slate-400 cursor-not-allowed'
                      : 'text-slate-600 hover:text-slate-800 hover:bg-slate-100'
                  }`}
                  title={isLoadingSuggestions ? '正在获取建议...' : '获取新建议'}
                >
                  <RefreshCw size={16} className={isLoadingSuggestions ? 'animate-spin' : ''} />
                </button>
              </div>
            </>
          ) : (
            <div className="mx-4 mb-4 p-4 bg-gray-50 border border-gray-200 rounded-xl text-center">
              <div className="text-gray-500 text-sm mb-2">暂无新建议</div>
              <button
                onClick={async () => {
                  // 防止重复点击
                  if (isLoadingSuggestions) return
                  
                  // 强制刷新建议（清除缓存）
                  localStorage.removeItem(SUGGESTIONS_CACHE_KEY)
                  localStorage.removeItem(SUGGESTIONS_CACHE_TIME_KEY)
                  await loadAISuggestions(true)
                }}
                disabled={isLoadingSuggestions}
                className={`p-2 rounded-lg transition-colors ${
                  isLoadingSuggestions
                    ? 'bg-slate-400 text-white cursor-not-allowed'
                    : 'bg-blue-600 text-white hover:bg-blue-700'
                }`}
                title={isLoadingSuggestions ? '正在获取建议...' : '获取建议'}
              >
                <RefreshCw size={16} className={isLoadingSuggestions ? 'animate-spin' : ''} />
              </button>
            </div>
          )}
        </div>
      )}

      {/* 任务列表 */}
      <div className="pb-8">
        {activeTab === 'today' && (
          totalTasks === 0 ? (
            <EmptyState />
          ) : (
            <>
              <TaskSection
                title="已过期"
                tasks={tasks.overdue}
                onToggleComplete={handleToggleComplete}
                onTaskClick={handleTaskClick}
                onDeleteTask={handleDeleteTask}
              />
              <TaskSection
                title="今天"
                tasks={tasks.today}
                onToggleComplete={handleToggleComplete}
                onTaskClick={handleTaskClick}
                onDeleteTask={handleDeleteTask}
              />
              <TaskSection
                title="接下来"
                tasks={tasks.upcoming}
                onToggleComplete={handleToggleComplete}
                onTaskClick={handleTaskClick}
                onDeleteTask={handleDeleteTask}
              />
              <TaskSection
                title="无日期"
                tasks={tasks.noDate}
                onToggleComplete={handleToggleComplete}
                onTaskClick={handleTaskClick}
                onDeleteTask={handleDeleteTask}
              />
            </>
          )
        )}
        
        {activeTab === 'recurring' && (
          <div className="mx-4 p-8 text-center">
            <div className="w-16 h-16 bg-purple-100 rounded-full flex items-center justify-center mx-auto mb-4">
              <Repeat size={24} className="text-purple-600" />
            </div>
            <h3 className="text-lg font-semibold text-slate-900 mb-2">重复任务</h3>
            <p className="text-slate-600 mb-4">点击下方按钮查看和管理重复任务</p>
            <button
              onClick={() => navigate('/recurring')}
              className="px-6 py-3 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors"
            >
              查看重复任务
            </button>
          </div>
        )}
        
        {activeTab === 'all' && (
          <div className="mx-4 p-8 text-center">
            <div className="w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-4">
              <List size={24} className="text-blue-600" />
            </div>
            <h3 className="text-lg font-semibold text-slate-900 mb-2">全部任务</h3>
            <p className="text-slate-600 mb-4">此功能即将推出，敬请期待</p>
          </div>
        )}
      </div>

      {/* 筛选面板 */}
      <TaskFilterPanel
        isOpen={showFilterPanel}
        onClose={() => setShowFilterPanel(false)}
        filters={filters}
        sortBy={sortBy}
        sortDirection={sortDirection}
        onFiltersChange={handleFiltersChange}
        onSortChange={handleSortChange}
        onReset={handleResetFilters}
      />

      {/* 通知提示 */}
      {notification && (
        <div className={`fixed bottom-24 left-4 right-4 z-[60] p-4 rounded-lg shadow-lg ${
          notification.type === 'success' ? 'bg-green-500 text-white' :
          notification.type === 'error' ? 'bg-red-500 text-white' :
          'bg-blue-500 text-white'
        }`}>
          <p className="text-center font-medium">{notification.message}</p>
        </div>
      )}
      </div>
    </PageTransition>
  )
}
